package com.jeesite.modules.kj.api.controller.member;


import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.jeesite.common.config.Global;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.aliyun.oss.bean.AliyunOSS;
import com.jeesite.modules.aliyun.oss.service.impl.OssFileUploadServiceExtendImpl;
import com.jeesite.modules.kj.api.vo.request.RegisterRequestVo;
import com.jeesite.modules.kj.api.vo.request.WechatRequestVo;
import com.jeesite.modules.kj.api.vo.response.RegisterResponseVo;
import com.jeesite.modules.kj.api.vo.response.WechatResponseVo;
import com.jeesite.modules.kj.api.wechatUtils.WechatHelper;
import com.jeesite.modules.kj.api.enumCode.UnicomResponseEnums;
import com.jeesite.modules.kj.api.vo.responseVo.ResponseBean;
import com.jeesite.modules.kj.entity.KjMember;
import com.jeesite.modules.kj.service.KjMemberService;
import com.jeesite.modules.kj.utils.ImageUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Author:hzy
 * Date:2021/07/04
 * Description:登陆注册
 */
@Api(value = "登陆注册api", tags = {"登陆注册api"})
@Slf4j
@Controller
@RequestMapping(value = "/api/session")
public class SessionController {
    private final static Logger logger = LoggerFactory.getLogger(SessionController.class);

    @Value("${weChat.config.appId}")
    private String appId;
    @Value("${weChat.config.appSecret}")
    private String appSecret;

    @Autowired
    private KjMemberService kjMemberService;

    @Value("${oss.bucketName}")
    String bucketName;
    @Value("${oss.endPoint}")
    String endPoint;
    @Value("${oss.downloadHost}")
    String downloadHost;


    @Value("${oss.endPoint}")
    private String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;

    OSSClient ossClient;

    @Autowired
    OssFileUploadServiceExtendImpl ossFileUploadServiceExtend;

    @Autowired
    AliyunOSS aliyunOSS;

    /**
     * 注册
     * */
    @ApiOperation(value = "注册用户", notes = "注册用户")
    @PostMapping(value = "register")
    @ResponseBody
    public ResponseBean<RegisterResponseVo> register(@Valid RegisterRequestVo registerRequestVo) {
        KjMember where = new KjMember();
        where.setMobile(registerRequestVo.getMobile());
        if(StringUtils.isNotBlank(registerRequestVo.getHeadimg())) {

            String name = StringUtils.getRandomStr(32);
            String ext = "png";
            String path = DateUtils.getDate("yyyyMM") + "/";
            String filePath = path + name + "." + ext;
            byte[] bs = ImageUtil.getNetImageByte(registerRequestVo.getHeadimg());

            ossClient = aliyunOSS.getOssClient();
            if(ossClient == null){
                ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            }
            ossFileUploadServiceExtend.uploadFile(ossClient, bs, filePath);
            String url = downloadHost + "/" + filePath;
            registerRequestVo.setHeadimg(url);
        }
        KjMember member = kjMemberService.getFirstMember(where);
        if(member == null){
            member = registerRequestVo.convertToMember();
            if(!member.getName().matches("^[\\u4e00-\\u9fa5]{2,30}$")) {
                return new ResponseBean(Global.FALSE, UnicomResponseEnums.ERROR_IDCODE.getCode(), "用户名应为2-30个汉字");
            }
            kjMemberService.save(member);
            return new ResponseBean(new RegisterResponseVo(member));
        }else{
            return new ResponseBean(Global.FALSE, UnicomResponseEnums.REPEAT_REGISTER.getCode(), "该手机号已注册，请直接登陆");
        }
    }

    /**
     * 获取openid
     * */
    @ApiOperation(value = "通过code获取openid并登陆", notes = "通过code获取openid并登陆，并返回sessionkey用于获取手机号")
    @PostMapping(value = "loginByCode")
    @ResponseBody
    public ResponseBean<WechatResponseVo> loginByCode(@Valid WechatRequestVo wechatVoRequestVo) {
        JSONObject result = WechatHelper.oauth2GetOpenid(appId, wechatVoRequestVo.getCode(), appSecret);
        log.debug("【获取openid】 result={}", result);

        ResponseBean responseBean = null;
        if (null != result) {
            Integer errcode = (null != result.get("errcode") && !"null".equals(result.get("errcode").toString())) ? Integer.parseInt(result.get("errcode").toString()) : 0;
            String errmsg = (null != result.get("errmsg") && !"null".equals(result.get("errmsg").toString())) ? result.get("errmsg").toString() : "";
            switch (errcode) {
                case 0:
                    KjMember where = new KjMember();
                    where.setWxopenid(result.getString("openid"));
                    KjMember kjMember = kjMemberService.getFirstMember(where);
                    WechatResponseVo vo = new WechatResponseVo();
                    vo.setSession_key(result.getString("sessionKey"));
                    vo.setOpenid(result.getString("openid"));
                    if (kjMember == null) {
                        return new ResponseBean<>(Global.TRUE, vo);
                    } else {
                        vo.setEntity(kjMember);
                        responseBean = new ResponseBean(vo);
                    }
                    break;
                case -1:
                    responseBean = new ResponseBean(Global.FALSE, null, UnicomResponseEnums.WECHAT_ERROR);
                    break;
                case 40029:
                    responseBean = new ResponseBean(Global.FALSE, null, UnicomResponseEnums.WECHAT_NO_CODE);
                    break;
                case 45011:
                    responseBean = new ResponseBean(Global.FALSE, null, UnicomResponseEnums.WECHAT_MAX_OUT);
                    break;
                default:
                    responseBean = new ResponseBean(Global.FALSE, String.valueOf(errcode), errmsg);
                    break;
            }
        }
        return responseBean;
    }



    /**
     * 根据手机号登陆小程序
     * */
//    @UserLoginToken
    @ApiOperation(value = "获取微信授权手机号", notes = "获取微信授权手机号")
    @PostMapping(value = "getWxMobile")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "session_key", value = "session_key", required = true, example = "fdfwer345343345dsf24"),
            @ApiImplicitParam(name = "ivStr", value = "ivStr", required = true, example = "1269889602083995648"),
            @ApiImplicitParam(name = "encryptedData", value = "encryptedData", required = true, example = "1269889602083995648")
    })
    public ResponseBean<WechatResponseVo> login(
                                                @RequestParam("session_key") String session_key,
                                                @RequestParam("ivStr") String ivStr,
                                                @RequestParam("encryptedData") String encryptedData) {
        try {
            String decrypt = WechatHelper.decrypt(session_key, ivStr, encryptedData);
            JSONObject jsonObject = JSONObject.parseObject(decrypt);
            String phoneNumber = jsonObject.getString("phoneNumber");
            KjMember where = new KjMember();
            where.setMobile(phoneNumber);
            KjMember kjMember = kjMemberService.getFirstMember(where);
            WechatResponseVo vo = new WechatResponseVo();
            if(kjMember != null){
                vo.setEntity(kjMember);
            }else {
                vo.setMobile(phoneNumber);
            }
            return new ResponseBean(vo);
        } catch (Exception e) {
            log.error("解密报错：" + e.getMessage());
            return new ResponseBean(Global.FALSE, null, UnicomResponseEnums.FAIL_GETDATA);
        }
    }

}
